#include <iostream>
#include <string>
#include "Reactor.hpp"
#include "Listener.hpp"
#include "Channel.hpp"
#include "Log.hpp"
#include "Common.hpp"
#include "Protocol.hpp"
#include "Translation.hpp"
using namespace std;
void Usage(string proc)
{
    cerr << " Usage: " << proc << " port" << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
    }
    ConsoleLogStrategy();
    uint16_t port = stoi(argv[1]);
    // 1.业务模块
    shared_ptr<Translation> translation = make_shared<Translation>();
    // 2.协议模块
    shared_ptr<Protocol> protocol = make_shared<Protocol>([&translation](Request &req) -> Respond
                                                          { return translation->Execute(req); });
    // 3.Listener模块
    shared_ptr<Connection> conn = make_shared<Listener>(port);
    conn->RegisterHandler([&protocol](string &inbuffer) -> string { 
        LOG(LogLevel::DEBUG) << "进入到匿名函数中...";
        string response_str;
        while (true)
        {
            string package;
            if (!protocol->DeCode(inbuffer, &package))
                break;
            // 我敢保证，我的packge一定是一个完整的请求，是字节流的
            response_str += protocol->Execute(package);
        }
        LOG(LogLevel::DEBUG) << "结束匿名函数中...: " << response_str;
        return response_str;
    });

    // reactor模块
    unique_ptr<Reactor> R = make_unique<Reactor>();
    R->AddConnection(conn);

    R->Loop();

    return 0;
}